package com.example.demo.service.impl;

import com.example.demo.dao.TbMessageDao;
import com.example.demo.entity.TbMessageEntity;
import com.example.demo.service.TbMessageService;
import javassist.runtime.Desc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TbMessageServiceImpl implements TbMessageService {

    TbMessageDao messageDao;
    @Autowired
    public TbMessageServiceImpl(TbMessageDao messageDao) {
        this.messageDao = messageDao;
    }

    public void deleteMessageById(int [] ids) {
        for (int id : ids) {
            messageDao.deleteById(id);
        }
    }

    public Map<String, Object> getMessageByPage(Integer index, Integer size) {
        if(index <= 0) {
            index = 1;
        }
        if(size <= 0) {
            size = 10;
        }
        Sort sort = Sort.by(Sort.Order.desc("messageDatetime"));
        Pageable pageable = PageRequest.of(index - 1, size, sort);
        Page<TbMessageEntity> messagePage = messageDao.findAll(pageable);
        Map<String, Object> result = new HashMap<>();
        result.put("result", messagePage.getContent());
        result.put("total", messagePage.getTotalElements());
        return result;
    }
}
